<?php

namespace App\Models;

use App\Http\Controllers\Admin\CommonController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 在线办证
 * Class OnlineRegistrationModel
 * @package app\common\model
 */
class OnlineRegistration extends BaseModel
{

    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'online_registration';



    //在其他一卡通办过证的提示语
    public $contrastMsg = '该读者身份证(证件类型)证件号码已存在！一个证件类型/号码不能办多个证！';
    public $repetitionCertificateMsg = '系统检测到您之前在其他一卡通馆办理过读者证，如需在本馆办理读者证，请证件类型选择“其他”，仍然输入身份证号码，请重新选择，谢谢！支付押金将原路退回！';



    /**
     * 获取读者证号，信用证  默认从 01030104000001   开始                                                      
     *               ABC证的号段是 01030101025601 -01030101025800 
     * 
     * 读者证类型  $card_type                                     
     */
    public function getReaderId($card_type)
    {
        //判断之前是否有未支付的读者证号，重新释放
        $onlineRegistrationModelObj = new OnlineRegistration();
        // $old_reader_id_arr = $onlineRegistrationModelObj
        //             ->where('is_pay' , 2)
        //             ->column('reader_id');
        // if(!empty($old_reader_id_arr)){
        //     $old_reader_id = $onlineRegistrationModelObj
        //             ->where('is_pay' , '<>' , 2)
        //             ->where('create_time' , '<' , date('Y-m-d H:i:s' , strtotime("-2 hour")))
        //             ->whereNotIn('reader_id' , $old_reader_id_arr)
        //             ->value('reader_id');

        //     if(!empty($old_reader_id)) return $old_reader_id;
        // }

        //获取现在最大的一个读者证
        if ($card_type == 28) {
            //先把删除的几个读者证号，分配完

            //获取新书最大一个条形码
            // if(empty($max_barcode)) {
            $max_reader_id = $onlineRegistrationModelObj
                ->where('reader_id', 'like', '200%')
                ->lockForUpdate()
                ->max('reader_id');

            if (empty($max_reader_id)) {
                $max_reader_id = '200000000';
            }
            // }
        } else {
            //获取新书最大一个读者证
            //  if(empty($max_barcode)) {
            $max_reader_id = $onlineRegistrationModelObj
                ->where('reader_id', 'like', '200%')
                ->lockForUpdate()
                ->max('reader_id');

            if (empty($max_reader_id)) {
                $max_reader_id = '200000000';
            }
            //最大不能超过10000000
            if ($max_reader_id == '29999999') {
                return false;
            }
            //  }
        }

        //   $max_reader_id = substr($max_reader_id, 3);
        $max_reader_id = $max_reader_id + 1;
        //  $max_reader_id = '100' . $max_reader_id;

        //跳过某一个
        // if ($max_reader_id == '01030104007216') {
        //     $max_reader_id = '01030104007217';
        // }

        return $max_reader_id;
    }
    /**
     * 证件类型
     */
    public function getCertificateType()
    {
        $data[] = ['certificate_type' => '1', 'certificate_name' => '身份证'];
        $data[] = ['certificate_type' => '2', 'certificate_name' => '其他'];
        return $data;
    }

    /**
     * 获取在线办证类型
     * shop_id = 1  渝北区图书馆     //测试环境55 ，正式环境28
     */
    public function getCardType($shop_id = 1, $card_type = null)
    {
        $data = [
            '1' => [
                //'55' => ['card_type' => '55', 'card_name' => '免押金信用证', 'cash' => 0],
                '28' => ['card_type' => '28', 'card_name' => '免押金信用证', 'cash' => 0],
                '9'  => ['card_type' => '9', 'card_name' => '读者证A证(押金100元)', 'cash' => 100],
                '11' => ['card_type' => '11', 'card_name' => '读者证B证(押金200元)', 'cash' => 200],
                '12' => ['card_type' => '12', 'card_name' => '读者证C证(押金500元)', 'cash' => 500],
            ],
            '2' => [
                //'55' => ['card_type' => '55', 'card_name' => '免押金信用证', 'cash' => 0],
                '28' => ['card_type' => '28', 'card_name' => '免押金信用证', 'cash' => 0],
                '9'  => ['card_type' => '9', 'card_name' => '读者证A证(押金100元)', 'cash' => 100],
                '11' => ['card_type' => '11', 'card_name' => '读者证B证(押金200元)', 'cash' => 200],
                '12' => ['card_type' => '12', 'card_name' => '读者证C证(押金500元)', 'cash' => 500],
            ]
        ];

        return !empty($card_type) ? (empty($data[$shop_id]) ? null : $data[$shop_id][$card_type]) : (empty($data[$shop_id]) ? null : $data[$shop_id]);
    }

    /**
     * 前端获取在线办证类型 （身份证类型）
     */
    public function getCardByFront($card_type = null)
    {
        $data = [
            //'55'=>['card_type' => '55', 'card_name' => '免押金信用证', 'cash' => 0],
            '28' => ['card_type' => '28', 'card_name' => '免押金信用证', 'cash' => 0],
            '9'  => ['card_type' => '9', 'card_name' => '读者证A证(押金100元)', 'cash' => 100],
            '11' => ['card_type' => '11', 'card_name' => '读者证B证(押金200元)', 'cash' => 200],
            '12' => ['card_type' => '12', 'card_name' => '读者证C证(押金500元)', 'cash' => 500],
        ];

        return !empty($card_type) ? $data[$card_type] : $data;
    }

    /**
     * 前端获取在线办证类型 （其他类型，只用于其他类型对应的读者证类型，无其他作用）
     */
    public function getCardByFrontOther()
    {
        $data = [
            //'55'=>['card_type' => '55', 'card_name' => '免押金信用证', 'cash' => 0],
            '28' => ['card_type' => '28', 'card_name' => '免押金信用证', 'cash' => 0],
        ];

        return $data;
    }

    /**
     * 列表获取在线办证类型（办证合计）
     */
    public function getCardByFrontList($card_type)
    {
        $data = [
            //'55'=>['card_type' => '55', 'card_name' => '免押金信用证', 'cash' => 0],
            '28' => ['card_type' => '28', 'card_name' => '免押金信用证', 'cash' => 0],
            '9'  => ['card_type' => '9', 'card_name' => '读者证A证(押金100元)', 'cash' => 100],
            '11' => ['card_type' => '11', 'card_name' => '读者证B证(押金200元)', 'cash' => 200],
            '12' => ['card_type' => '12', 'card_name' => '读者证C证(押金500元)', 'cash' => 500],
        ];

        return $data[$card_type];
    }


    /**
     * 获取用户文化程度
     */
    public function getCulture($culture_id = null)
    {
        $culture_data = [
            ['id' => 1, 'name' => '其它'],
            ['id' => 2, 'name' => '研究生'],
            ['id' => 3, 'name' => '本科'],
            ['id' => 4, 'name' => '大专'],
            ['id' => 5, 'name' => '中专'],
            ['id' => 6, 'name' => '高中'],
            ['id' => 7, 'name' => '初中'],
            ['id' => 8, 'name' => '小学']
        ];

        if (empty($culture_id)) {
            return $culture_data;
        }

        $culture_data = array_column($culture_data, 'name', 'id');
        return isset($culture_data[$culture_id]) ? $culture_data[$culture_id] : '未知';
    }

    /**
     * 获取用户职业
     */
    public function getPosition($position_id = null)
    {
        $position_data = [
            ['id' => 1, 'name' => '其它'],
            ['id' => 2, 'name' => '工人'],
            ['id' => 3, 'name' => '教师'],
            ['id' => 4, 'name' => '农民'],
            ['id' => 5, 'name' => '学生'],
            ['id' => 6, 'name' => '军警'],
            ['id' => 7, 'name' => '公务员'],
            ['id' => 8, 'name' => '科技人员'],
            ['id' => 9, 'name' => '医务人员'],
            ['id' => 10, 'name' => '职员'],
            ['id' => 11, 'name' => '服务员'],
            ['id' => 12, 'name' => '个体户'],
            ['id' => 13, 'name' => '待业'],
        ];

        if (empty($position_id)) {
            return $position_data;
        }
        $position_data = array_column($position_data, 'name', 'id');
        return isset($position_data[$position_id]) ? $position_data[$position_id] : '未知';
    }

    /**
     * 动态参数
     * 配置界面选项，多个用“|”链接     1.头像(弃用) 2.居住地 3.身份证正反面 4.电子邮箱 5.邮政编码 6.座机号码 7.读者职业 8.文化程度 9.工作单位 10.备注
     */
    public function dynamicParam()
    {
        // $data = '1|2|3|4|5|6|7|8|9|10';
        $data = OnlineRegistrationConfig::where('id', 1)->value('real_info');
        return $data;
    }


    /**
     * 办证统计数据
     * @param shop_id 书店id 默认全部
     * @param keywords_type  检索条件   0、全部  1、读者证号  2、身份证号码 3 姓名 默认 0
     * @param keywords  检索条件
     * @param card_type  类型  默认全部
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param certificate_type		证件类型  0、全部 1 为身份证  2 为其他证
     * @param certificate_manage_id		办证操作人
     * @param settle_sponsor_manage_id		发起结算操作人
     * @param settle_affirm_manage_id		确认结算操作人
     * @param source		办证来源 1前端 2后台
     * @param status		是否领取 1 已领取  2 待领取  3 无需领取   4、已注销
     * @param node		是否写入成功  1 成功  2 失败
     * @param select_way  查询方式  1 分页列表  2 人次  3 总价格 4总数量
     * @param is_pay  支付状态 1 未支付 2 已支付    3支付异常， 4 订单已失效 5 .已退款
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function lists($params)
    {
        $field = $params['field'] ?? ['*'];
        $keywords = $params['keywords'] ?? null;
        $keywords_type = $params['keywords_type'] ?? null;
        $shop_id = $params['shop_id'] ?? null;
        $start_time = $params['start_time'] ?? null;
        $end_time = $params['end_time'] ?? null;
        $settle_state = $params['settle_state'] ?? null;
        $card_type = $params['card_type'] ?? null;
        $certificate_type = $params['certificate_type'] ?? null;
        $certificate_manage_id = $params['certificate_manage_id'] ?? null;
        $settle_sponsor_manage_id = $params['settle_sponsor_manage_id'] ?? null;
        $settle_affirm_manage_id = $params['settle_affirm_manage_id'] ?? null;
        $shop_all_id = $params['shop_all_id'] ?? null;
        $source = $params['source'] ?? null;
        $status = $params['status'] ?? null;
        $is_pay = $params['is_pay'] ?? [2, 3, 5];
        $node = $params['node'] ?? null;
        $select_way = $params['select_way'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $page = $params['page'] ?? 1;
        if (empty($field)) {
            $field = ['*'];
        }

        //   DB::enableQueryLog();
        $res = $this->select($field)
            ->where(function ($query) use ($keywords_type, $keywords) {
                if (!empty($keywords)) {
                    if (empty($keywords_type)) {
                        $query->Orwhere('reader_id', 'like', '%' . $keywords . '%')
                            ->Orwhere('username', 'like', '%' . $keywords . '%')
                            ->Orwhere('id_card', 'like', '%' . $keywords . '%');
                    } else {
                        switch ($keywords_type) {
                            case 1:
                                $query->where('reader_id', 'like', '%' . $keywords . '%');
                                break;
                            case 2:
                                $query->where('id_card', 'like', '%' . $keywords . '%');
                                break;
                            case 3:
                                $query->where('username', 'like', '%' . $keywords . '%');
                                break;
                        }
                    }
                }
            })->where(function ($query) use ($shop_id, $card_type, $start_time, $end_time, $settle_state, $shop_all_id, $certificate_manage_id, $certificate_type, $settle_sponsor_manage_id, $settle_affirm_manage_id, $source, $status, $is_pay, $node) {
                if (!empty($shop_id)) {
                    $query->where("shop_id", $shop_id);
                }
                //线下办证需要验证，前台办证无需验证
                if ($source == 2) {
                    $query->whereIn('shop_id', $shop_all_id);
                }

                if (!empty($settle_state)) {
                    $query->where("settle_state", $settle_state);
                }
                if (!empty($certificate_type)) {
                    $query->where("certificate_type", $certificate_type);
                }
                if (!empty($certificate_manage_id)) {
                    $query->where("certificate_manage_id", $certificate_manage_id);
                }
                if (!empty($card_type)) {
                    $query->where("card_type", $card_type);
                }
                if (!empty($source)) {
                    $query->where("source", $source);
                }
                if (!empty($status)) {
                    $query->where("status", $status);
                }
                if (!empty($node)) {
                    $query->where("node", $node);
                }
                if (!empty($is_pay)) {
                    $is_pay = !is_array($is_pay) ? explode(',', $is_pay) : $is_pay;
                    $query->whereIn("is_pay", $is_pay);
                }
                if (!empty($start_time) && !empty($end_time)) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }

                if (!empty($settle_sponsor_manage_id)) {
                    $query->where("settle_sponsor_manage_id", $settle_sponsor_manage_id);
                }
                if (!empty($settle_affirm_manage_id)) {
                    $query->where("settle_affirm_manage_id", $settle_affirm_manage_id);
                }
            })
            ->whereIn('is_pay', [2, 3, 5])
            ->orderByDesc("id");

        if ($select_way == 1) {
            $res = $res->paginate($limit)
                ->toArray();
        } elseif ($select_way == 2) {
            $res = $res->groupBy('user_id')->pluck('id');
            return count($res);
        } elseif ($select_way == 3) {
            $res = $res->sum('cash');
        } elseif ($select_way == 4) {
            $res = $res->count();
        }

        //    dump(DB::getQueryLog());die;
        if ($select_way == 1) {
            $commonControllerObj = new CommonController();
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['certificate_type_name'] = $val['certificate_type'] == 1 ? '身份证' : '其他';
                $res['data'][$key]['certificate_manage_name'] = !empty($val['certificate_manage_id']) ? Manage::getManageNameByManageId($val['certificate_manage_id']) : '';
                $res['data'][$key]['settle_sponsor_manage_name'] = !empty($val['settle_sponsor_manage_id']) ? Manage::getManageNameByManageId($val['settle_sponsor_manage_id']) : '';
                $res['data'][$key]['settle_affirm_manage_name'] = !empty($val['settle_affirm_manage_id']) ? Manage::getManageNameByManageId($val['settle_affirm_manage_id']) : '';

                $res['data'][$key]['card_name'] = $this->getCardByFrontList($val['card_type'])['card_name'];
                $res['data'][$key]['certificate_type'] = $val['certificate_type'] == 1 ? '身份证' : '其他';
                $shop_name = empty($val['shop_id']) ? '' : Shop::where('id', $val['shop_id'])->value('name');
                $res['data'][$key]['shop_name'] = $shop_name;

                $res['data'][$key][$commonControllerObj->list_index_key] = $commonControllerObj->addSerialNumberOne($key, $page, $limit);
            }
            $res = $commonControllerObj->disPageData($res);
        }
        return $res;
    }
}
